package com.suyang.syt.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.dao.interfaces.DictionaryDao;
import com.suyang.syt.model.Dictionary;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.service.interfaces.DictionaryService;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.JsonUtil;

/** 字典信息通用CRUD方法，适用于id name两个字段的字典数据的CRUD */
@Service
public class DictionaryServiceImpl implements DictionaryService {

	@Resource
	private DictionaryDao dictionaryDao;

	@Override
	public AjaxObj add(String name, String code, long pid, int orderIndex) throws Exception {
		if (EmptyUtil.isEmpty(name)) {
			return new AjaxObj(0, "数据字典名称不能为空!");
		}
		long count = dictionaryDao.countByName(name, pid);
		if (count > 0) {
			return new AjaxObj(0, "已经存在了该字典,请更换名称!");
		}
		if (pid != 0) {
			Dictionary parent = dictionaryDao.load(pid);
			if (parent == null) {
				return new AjaxObj(0, "字典加载错误,请联系管理员!");
			}
			if (parent.getPid() != 0) {
				return new AjaxObj(0, "数据字典只能支持二级菜单!");
			}
			if ("open".equals(parent.getState())) {
				parent.setState("closed");
				dictionaryDao.update(parent);
			}
		}
		dictionaryDao.add(new Dictionary(name, code, pid, orderIndex));
		setAddCache(name, pid);
		return new AjaxObj(1, "字典创建成功!");
	}

	private void setAddCache(String name, long pid) {
		Map<String, List<Dictionary>> map = BeanFactoryContext.getDictionarys();
		if (pid == 0) {
			map.put(name, null);
		} else {
			Dictionary data = dictionaryDao.load(pid);
			if (data != null) {
				map.put(data.getName(), dictionaryDao.listByPid(pid));
			}
		}
		BeanFactoryContext.setDictionarys(map);
	}

	@Override
	public AjaxObj update(long id, String name, String code, int orderIndex) throws Exception {
		if (EmptyUtil.isEmpty(name)) {
			return new AjaxObj(0, "数据字典名称不能为空!");
		}
		Dictionary dictionary = dictionaryDao.load(id);
		if (dictionary == null) {
			return new AjaxObj(0, "字典加载失败,请联系管理员!");
		}
		long count = dictionaryDao.countByName(name, dictionary.getPid());
		if (count > 0 && !name.equals(dictionary.getName())) {
			return new AjaxObj(0, "已经存在该数据字典,请更换名称!");
		}
		dictionary.setName(name);
		dictionary.setCode(code);
		dictionary.setOrderIndex(orderIndex);
		dictionaryDao.update(dictionary);
		setUpdateCache(name, dictionary);
		return new AjaxObj(1, "字典更新成功!");
	}

	private void setUpdateCache(String name, Dictionary dictionary) {
		Map<String, List<Dictionary>> map = BeanFactoryContext.getDictionarys();
		if (dictionary.getPid() == 0) {
			List<Dictionary> list = map.get(dictionary.getName());
			map.put(name, list);
			map.remove(dictionary.getName());
		} else {
			Dictionary parent = dictionaryDao.load(dictionary.getPid());
			List<Dictionary> list = map.get(parent.getName());
			if (EmptyUtil.isNotEmpty(list)) {
				for (int i = 0; i < list.size(); i++) {
					if (dictionary.getId() == list.get(i).getId()) {
						list.get(i).setName(name);
					}
				}
			}
		}
		BeanFactoryContext.setDictionarys(map);
	}

	@Override
	public AjaxObj deletes(String ids) throws Exception {
		if (EmptyUtil.isEmpty(ids)) {
			return new AjaxObj(0, "请选择您要删除的字典!");
		}
		dictionaryDao.deletes(ids);
		setDeleteCache(ids);
		return new AjaxObj(1, "删除数据字典成功!");
	}

	private void setDeleteCache(String ids) {
		Map<String, List<Dictionary>> map = BeanFactoryContext.getDictionarys();
		String[] idsArr = ids.split(",");
		if (idsArr != null && idsArr.length > 0) {
			Dictionary dictionary = null;
			for (String id : idsArr) {
				dictionary = dictionaryDao.load(Long.parseLong(id));
				if (dictionary != null) {
					if (dictionary.getPid() == 0) {
						map.remove(dictionary.getName());
					} else {
						Dictionary parent = dictionaryDao.load(dictionary.getPid());
						if (parent != null) {
							List<Dictionary> list = map.get(parent.getName());
							if (EmptyUtil.isNotEmpty(list)) {
								for (int i = 0; i < list.size(); i++) {
									if (dictionary.getId() == list.get(i).getId()) {
										list.remove(i);
									}
								}
							}
						}
					}
				}
			}
		}
		BeanFactoryContext.setDictionarys(map);
	}

	@Override
	public PagerEasyUI<Dictionary> listByEasyUI(int page, int rows, String sort, String order, String createDate1, String createDate2) {
		return dictionaryDao.listByEasyUI(page, rows, sort, order, createDate1, createDate2);
	}

	@Override
	public Dictionary load(long id) throws Exception {
		return dictionaryDao.load(id);
	}

	@Override
	public String initDictionary() throws Exception {
		Map<String, List<Dictionary>> map = new HashMap<String, List<Dictionary>>();
		List<Dictionary> types = dictionaryDao.listByPid(0);
		List<Dictionary> datas = null;
		if (EmptyUtil.isNotEmpty(types)) {
			for (Dictionary type : types) {
				datas = dictionaryDao.listByPid(type.getId());
				if (EmptyUtil.isNotEmpty(datas)) {
					map.put(type.getName(), datas);
				}
			}
		}
		BeanFactoryContext.setDictionarys(map);
		return JsonUtil.toJson(map);
	}

	@Override
	public List<Dictionary> listTreegrid(long id) {
		return dictionaryDao.listByPid(id);
	}

}
